package com.heima.search.service;

import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Set;

@Service
public class RedisService {

    @Autowired
    private StringRedisTemplate redisTemplate;

//    redis的key前缀
    private String PRE_FIX = "ld:search:word:";

    /**
     * 保存用户搜索关键词
     * @param searchWords
     * @param userId
     */
    @Async("taskExecutor")
    public void saveWords(String searchWords, Integer userId,String equipmentId) {

        String key = getKey(userId,equipmentId);
//        保存关键词，记录搜索的次数
        redisTemplate.opsForZSet().incrementScore(key,searchWords,1);

    }

    /**
     * 查询关键词列表
     * @param userId
     * @param equipmentId
     * @return
     */
    public Set<String> getWords(Integer userId,String equipmentId){
        String key = getKey(userId, equipmentId);
        Set<String> set = redisTemplate.opsForZSet().reverseRange(key, 0, -1);
        return set;
    }

    /**
     * 删除
     * @param userId
     * @param equipmentId
     * @param words
     */
    public void removeWords(Integer userId,String equipmentId,String words){
        String key = getKey(userId, equipmentId);
        redisTemplate.opsForZSet().remove(key,words);
    }


    /**
     * 生成redis的key
     * @param userId
     * @param equipmentId
     * @return
     */
    private String getKey(Integer userId, String equipmentId) {
        if(userId != null && userId != 0){
            return PRE_FIX+userId.toString();
        }
        return PRE_FIX+equipmentId;
    }
}